package rest.home.coontuil;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author 柳新宽
 * @create 2022-04-28  10:11
 * @describe
 */
public class ConnUtil {
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    private static DataSource dataSource;
    //在静态块中对资源文件进行加载并且创建数据源对象
    static {
        try {
            Properties properties = new Properties();
            InputStream inputStream = ConnUtil.class.getResourceAsStream("/mysql.properties");
            properties.load(inputStream);
            //使用资源创建数据源对象
            dataSource = BasicDataSourceFactory.createDataSource(properties);//数据库连接池
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取数据库连接对象
    public static Connection getConn() throws SQLException {
        Connection conn = threadLocal.get(); //除了第一次 接下来每一次都是从threadLocal获取副本
        if(conn==null||conn.isClosed()){
            conn=dataSource.getConnection();//从数据库链接池中获取一个连接
            threadLocal.set(conn);
        }
        return conn;
    }
    //并发的时候 每一个线程得到是从连接池中获取的链接对象  接下此线程不管申请多少地链接都是同一个链接
    //关闭数据库连接对象
    public static void closeConn(){
        try {
            Connection conn = threadLocal.get();
            if(conn!=null&&!conn.isClosed()){
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            threadLocal.set(null);
        }
    }
}
